package com.mq.rabbitmq.point;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;


/**
 * Created by Administrator on 2017/8/3.
 */
public class Receive {

    /**
     * 自动应答无线重试，测试加入了新的字段，就得还会有问题吗
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public SimpleMessageListenerContainer messageContainer(ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.addQueues(new Queue(AmqpConfig.ROUTINGKEY));
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        //不手动确认模式，如果有异常，会重新消费
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                byte[] body = message.getBody();
                System.out.println("receiver start ===="+message.getMessageProperties().toString());
                //自动模式，会管这个确认关系吗
                try{
                    String g = null;
                    g.toString();
                }catch (Exception e){
                    throw e;
                }
                System.out.println("receiver end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<consume the message " + new String(body));
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
            }
        });
        return container;
    }
}
